const query = require('../db/mysql')
const {success, error} = require('../model/model')
class ListController {
    getList =  async(ctx) => {
        // id查询 模糊查询 排序  分页
        const {id, keyword, sortBy,sortType, pageIndex,pageSize} = ctx.query;
        let sql = `select * from blogs where 1=1 `
        let sqlCount = `select count(id) as total from blogs where 1=1 `
        if(id) {
            sql += `and id = ${id} `
            sqlCount += `and id = ${id} `
        }
        if(keyword) {
            sql += `and title like "%${keyword}%" `
            sqlCount += `and title like "%${keyword}%" `
        }
        if(sortBy && sortType) {
            sql += `order by ${sortBy} ${sortType} `
        }
        if(pageIndex && pageSize) {
            sql += `limit ${(pageIndex-1)*pageSize},${pageSize}`
        }
        const data = await query(sql)
        const count = await query(sqlCount)
        ctx.body = success({
            data: data,
            total: count[0].total
        })
    }
    addList = async(ctx) => {
        const {title,content,author} = ctx.request.body
        const sql = `insert into blogs(title, content,author,create_time) values("${title}","${content}","${author}","${Date.now()}")`
        const data = await query(sql)
        if(data.affectedRows === 1) {
            ctx.body = success({
                id:data.insertId
            })
        } else {
            ctx.body = error('编辑失败')
        }
    }
    editList =  async(ctx) => {
        const {title, content, id} = ctx.request.body;
        const sql = `update blogs set title="${title}",content="${content}" where id="${id}"`;
        const data = await query(sql)
        if(data.affectedRows === 1) {
            ctx.body = success('编辑成功')
        } else {
            ctx.body = error('编辑失败')
        }
    }
    delList = async(ctx) => {
        const {id} = ctx.params;
        const sql = `delete from blogs where id =${id}`;
        const data = await query(sql)
        if(data.affectedRows === 1) {
            ctx.body =  success('删除成功')
        } else {
            ctx.body = error('删除失败')
        }
    }
}

module.exports = new ListController()